package com.naiterui.common.repository.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.naiterui.common.repository.annotation.Query;
import com.naiterui.common.repository.annotation.QueryCriteria;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@SuppressWarnings("all")
public class QueryHelp {

    public static <R, Q extends QueryCriteria> Predicate getPredicate(Root<R> root, QueryCriteria query, CriteriaBuilder cb) {
        List<Predicate> list = new ArrayList<>();

        if (query == null) {
            return cb.and(list.toArray(new Predicate[0]));
        }
        try {
            List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());
            for (Field field : fields) {
                boolean accessible = field.isAccessible();
                field.setAccessible(true);
                Query q = field.getAnnotation(Query.class);
                if (q == null) {
                    field.setAccessible(accessible);
                    continue;
                }
                String propName = q.propName();
                String joinName = q.joinName();
                String blurry = q.blurry();
                String attributeName = isBlank(propName) ? field.getName() : propName;
                Class<?> fieldType = field.getType();
                Object val = field.get(query);
                if (ObjectUtil.isEmpty(val)) {
                    continue;
                }
                Join join = null;
                // 模糊多字段
                if (ObjectUtil.isNotEmpty(blurry)) {
                    String[] blurrys = blurry.split(",");
                    List<Predicate> orPredicate = Arrays.stream(blurrys)
                        .map(s -> cb.like(root.get(s).as(String.class), "%" + val.toString() + "%"))
                        .collect(Collectors.toList());
                    Predicate[] p = new Predicate[orPredicate.size()];
                    list.add(cb.or(orPredicate.toArray(p)));
                    continue;
                }
                if (ObjectUtil.isNotEmpty(joinName)) {
                    String[] joinNames = joinName.split(">");
                    for (String name : joinNames) {
                        join = ObjectUtil.isNotNull(join) ? join.join(name, q.join()) : root.join(name, q.join());
                    }
                }
                Expression<Object> objectExpression = getExpression(attributeName, join, root);
                Expression expression = objectExpression.as((Class<? extends Comparable>) fieldType);
                switch (q.type()) {
                    case EQUAL:
                        list.add(cb.equal(expression, val));
                        break;
                    case GREATER_THAN:
                        list.add(cb.greaterThanOrEqualTo(expression, (Comparable) val));
                        break;
                    case LESS_THAN:
                        list.add(cb.lessThanOrEqualTo(expression, (Comparable) val));
                        break;
                    case LESS_THAN_NQ:
                        list.add(cb.lessThan(expression, (Comparable) val));
                        break;
                    case INNER_LIKE:
                        list.add(cb.like(objectExpression.as(String.class), "%" + val.toString() + "%"));
                        break;
                    case LEFT_LIKE:
                        list.add(cb.like(objectExpression.as(String.class), "%" + val.toString()));
                        break;
                    case RIGHT_LIKE:
                        list.add(cb.like(objectExpression.as(String.class), val.toString() + "%"));
                        break;
                    case IN:
                        if (CollUtil.isNotEmpty((Collection<Long>) val)) {
                            list.add(objectExpression.in((Collection<Long>) val));
                        }
                        break;
                    case NOT_EQUAL:
                        list.add(cb.notEqual(objectExpression, val));
                        break;
                    case NOT_NULL:
                        list.add(cb.isNotNull(objectExpression));
                        break;
                    case BETWEEN:
                        List<Object> between = new ArrayList<>((List<Object>) val);
                        if (CollUtil.isNotEmpty(between)) {
                            list.add(cb.between(objectExpression.as((Class<? extends Comparable>) between.get(0).getClass()),
                                (Comparable) between.get(0), (Comparable) between.get(1)));
                        }
                        break;
                    default:
                        break;
                }
                field.setAccessible(accessible);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        int size = list.size();
        return cb.and(list.toArray(new Predicate[size]));
    }

    @SuppressWarnings("unchecked")
    private static <T, R> Expression<T> getExpression(String attributeName, Join join, Root<R> root) {
        return ObjectUtil.isNotEmpty(join) ? join.get(attributeName) : root.get(attributeName);
    }

    private static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        return IntStream.range(0, strLen).allMatch(i -> Character.isWhitespace(cs.charAt(i)));
    }

    private static List<Field> getAllFields(Class clazz, List<Field> fields) {
        if (clazz != null) {
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            getAllFields(clazz.getSuperclass(), fields);
        }
        return fields;
    }
}
